package me.shurufa.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.lsjwzh.widget.recyclerviewpager.RecyclerViewPager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import me.shurufa.R;
import me.shurufa.activities.CatalogWithDigestActivity;
import me.shurufa.adapter.HorizontalMarkAdapter;
import me.shurufa.adapter.HorizontalMyMarkAdapter;
import me.shurufa.event.EventObject;
import me.shurufa.model.Digest;
import me.shurufa.model.DigestListResponse;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.NetworkConstants;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;

/**
 * 点击书架上的书跳转到图书信息中针对我的书摘的Fragment
 *
 * @FileName: me.shurufa.fragments.MyAboutBookMarkFragment.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-02-04 18:19
 */
public class MyAboutBookMarkFragment extends BaseListFragment implements View.OnClickListener {

    @Bind(R.id.divider)
    View divider;
    @Bind(R.id.viewpager)
    RecyclerViewPager viewpager;
    @Bind(R.id.empty_view)
    RelativeLayout emptyView;
    @Bind(R.id.watch_digests)
    RelativeLayout watchDigests;

    HorizontalMyMarkAdapter markAdapter;
    ArrayList dataList;
    private long excerptedBookId;
    private long bookId;

    public static MyAboutBookMarkFragment newInstance(long excerptedBookId,long bookId) {
        MyAboutBookMarkFragment fragment = new MyAboutBookMarkFragment();
        Bundle args = new Bundle();
        args.putLong(Constants.ARG_EXCERPT_BOOKID, excerptedBookId);
        args.putLong(Constants.ARG_BOOK_ID,bookId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            excerptedBookId = getArguments().getLong(Constants.ARG_EXCERPT_BOOKID);
            bookId = getArguments().getLong(Constants.ARG_BOOK_ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_about_mark, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        watchDigests.setOnClickListener(this);
        dataList = new ArrayList();
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        viewpager.setLayoutManager(manager);
        markAdapter = new HorizontalMyMarkAdapter(this, dataList);
        mAdapter = markAdapter;
        viewpager.setVisibility(View.GONE);
        showEmptyView();
        viewpager.setAdapter(markAdapter);
        //set the left margin of first viewpage and the right margin of last viewpage
        viewpager.setHasFixedSize(true);
        viewpager.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int scrollState) {
//                updateState(scrollState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int i, int i2) {
//                mPositionText.setText("First: " + mRecyclerViewPager.getFirstVisiblePosition());
                int childCount = viewpager.getChildCount();
                int width = viewpager.getChildAt(0).getWidth();
                int padding = (viewpager.getWidth() - width) / 3;
                LogUtils.kLog().d("" + padding);
//                mCountText.setText("Count: " + childCount);
                for (int j = 0; j < childCount; j++) {
                    View v = recyclerView.getChildAt(j);
                    //往左 从 padding 到 -(v.getWidth()-padding) 的过程中，由大到小
                    float rate = 0;
                    ;
                    if (v.getLeft() <= padding) {
                        if (v.getLeft() >= padding - v.getWidth()) {
                            rate = (padding - v.getLeft()) * 1f / v.getWidth();
                        } else {
                            rate = 1;
                        }
                        v.setScaleY(1 - rate * 0.1f);
                        v.setScaleX(1 - rate * 0.1f);

                    } else {
                        //往右 从 padding 到 recyclerView.getWidth()-padding 的过程中，由大到小
                        if (v.getLeft() <= recyclerView.getWidth() - padding) {
                            rate = (recyclerView.getWidth() - padding - v.getLeft()) * 1f / v.getWidth();
                        }
                        v.setScaleY(0.9f + rate * 0.1f);
                        v.setScaleX(0.9f + rate * 0.1f);
                    }
                }
            }
        });
        viewpager.addOnPageChangedListener(new RecyclerViewPager.OnPageChangedListener() {
            @Override
            public void OnPageChanged(int oldPosition, int newPosition) {
                LogUtils.kLog().d("oldPosition:" + oldPosition + " newPosition:" + newPosition);
            }
        });

        viewpager.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (viewpager.getChildCount() < 3) {
                    if (viewpager.getChildAt(1) != null) {
                        if (viewpager.getCurrentPosition() == 0) {
                            View v1 = viewpager.getChildAt(1);
                            v1.setScaleY(0.9f);
                            v1.setScaleX(0.9f);
                        } else {
                            View v1 = viewpager.getChildAt(0);
                            v1.setScaleY(0.9f);
                            v1.setScaleX(0.9f);
                        }
                    }
                } else {
                    if (viewpager.getChildAt(0) != null) {
                        View v0 = viewpager.getChildAt(0);
                        v0.setScaleY(0.9f);
                        v0.setScaleX(0.9f);
                    }
                    if (viewpager.getChildAt(2) != null) {
                        View v2 = viewpager.getChildAt(2);
                        v2.setScaleY(0.9f);
                        v2.setScaleX(0.9f);
                    }
                }

            }
        });
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loadData(false);
    }

    private void loadData(final boolean isNew) {
        new RequestServerTask<DigestListResponse>(DigestListResponse.class) {

            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("excerptedBookId", excerptedBookId);
                params.put("token", Global.currentUser.token);
                params.put("page", 1);
                return HttpUtil.post(NetworkConstants.MY_DIGEST_GET_BY_BOOK, params);
            }

            @Override
            protected void onSuccess(DigestListResponse result) {
                bindData(result, isNew);
            }
        }.start();
    }

    @Override
    protected void bindData(BaseResponse response, boolean isNew) {
        super.bindData(response, isNew);
        if (markAdapter.getItemCount() == 0) {
            viewpager.setVisibility(View.GONE);
            showEmptyView();
        } else {
            viewpager.setVisibility(View.VISIBLE);
            hideEmptyView();
        }
    }

    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {
        DigestListResponse resp = (DigestListResponse) response;
        if (isNew) {
            markAdapter.clear();
        }
        markAdapter.append(resp.data);
    }

    @Override
    protected void showEmptyView() {
        emptyView.setVisibility(View.VISIBLE);
    }

    @Override
    protected void hideEmptyView() {
        emptyView.setVisibility(View.GONE);
    }

    @Override
    protected void setHasMore(boolean hasMore) {

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.watch_digests:
                intent = new Intent(getActivity(), CatalogWithDigestActivity.class);
                intent.putExtra(Constants.ARG_BOOK_ID, bookId);
                intent.putExtra(Constants.ARG_USER_ID,Global.getCurrentUid());
                startActivity(intent);
                break;
        }
    }

    public void onEventMainThread(EventObject object) {
        if (object.getEventAction().equals(Constants.ACTION_MODIFY_MY_DIGEST)){
            Digest digest = object.getDigest();
            if (digest!=null){
                for (int i = 0; i < dataList.size(); i++) {
                    if (digest.id==((Digest)dataList.get(i)).id){
                        if (dataList!=null&&markAdapter!=null) {
                            dataList.set(i, digest);
                            markAdapter.notifyDataSetChanged();
                        }
                        break;
                    }
                }
            }
        }
    }
}
